﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace StorageInterface
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            try
            {
                InitializeComponent();
                Load();
            }
            catch (Exception ex)
            {
                ErrorHandler.HandleError(ex.Message);
            }


 

        }

        private void UpdateElementWhithPartners()
        {
            #region partners
            var prtnrs = Data.GetAllPartners();

            PartnerTL.ItemsSource = prtnrs;//Data.GetAllPartners();
            AllFirmsCombo_1.Items.Clear();
            AllPartner_CB2.Items.Clear();
            
            
            AllFirmsCombo_1.Items.Add(new Partner() { Name = "Все партнеры", ID_Partner = -1 });

            foreach (var el in prtnrs)
            {
                AllFirmsCombo_1.Items.Add(el);
                AllPartner_CB2.Items.Add(el);
            }

            AllFirmsCombo_1.SelectedIndex = 0;
                       
            #endregion
        }
        private void UpdateWhithStorage()
        {
            Storage3CB.ItemsSource = Data.GetAllStorages();
        }
        private void Load()
        {

            UpdateElementWhithPartners();
            UpdateWhithStorage();
            RemainUC.Update();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BuyersUC.Visibility = System.Windows.Visibility.Hidden;
            TradeUC.Visibility = System.Windows.Visibility.Hidden;
            CashReportUC.Visibility = System.Windows.Visibility.Hidden;
            RemainUC.Visibility = System.Windows.Visibility.Hidden;
            ReportPLLBIUC.Visibility = System.Windows.Visibility.Hidden;
            if (ReportListBox.SelectedItem == null)
            {
                titleReportTextBlock.Text = "";                
                return;
            }
            titleReportTextBlock.Text = (ReportListBox.SelectedItem as ListBoxItem).Content as string;
            if (ReportListBox.SelectedItem == BuyersLBI)
            {
                BuyersUC.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            if (ReportListBox.SelectedItem == TradeLBI)
            {
                TradeUC.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            if (ReportListBox.SelectedItem == CashReportLBI)
            {
                CashReportUC.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            if (ReportListBox.SelectedItem == RemainLBI)
            {
                RemainUC.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            if (ReportListBox.SelectedItem == ReportPLLBI)
            {
                ReportPLLBIUC.Visibility = System.Windows.Visibility.Visible;
                return;
            }
        }

        private void ComboBoxItem_Selected(object sender, RoutedEventArgs e)
        {

        }

        #region Partners
        private void NewPartnerButton_Click(object sender, RoutedEventArgs e)
        {
            Partner p = Data.NewPartner();
            if (p == null)
                MessageBox.Show(this, "Не удалось добавить контрагента");
            UpdateElementWhithPartners();
            
            
        }
        private void PartnerParentTL_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            Partner p = PartnerParentTL.SelectedItem as Partner;
            InitInfoPanelPartner(p);
        }
        private void CancelPartnerButton_Click(object sender, RoutedEventArgs e)
        {
            Partner p = PartnerParentTL.SelectedItem as Partner;
            InitInfoPanelPartner(p);
        }

        private void SavePartnerButton_Click(object sender, RoutedEventArgs e)
        {
            Partner p = PartnerParentTL.SelectedItem as Partner;

            if (NameTB.Text == "" || NameTB.Text == null)
            {
                ErrorHandler.HandleError("Название компании не может быть пустой строкой");
                InitInfoPanelPartner(p);
                return;

            }

            EditFromInfoPanel(p);
            Data.UpdatePartner(p);
            InitInfoPanelPartner(p);
            
            PartnerTL.ItemsSource = Data.GetAllPartners();
        }
        private void InitInfoPanelPartner(Partner p)
        {
            if (p == null)
            {
                PartnerInfoPanel.IsEnabled = false;
                //ADiscTB.Clear();
                CodeTB.Clear();
                DiscTB.Clear();
                EmailTB.Clear();
                FactTB.Clear();
                FaxTB.Clear();
                KPPTB.Clear();
                LegalTB.Clear();
                NameTB.Clear();
                OKPOTB.Clear();
                PhoneTB.Clear();
                return;
            }
            PartnerInfoPanel.IsEnabled = true;
            CodeTB.Text = p.Code;
            EmailTB.Text = p.Email;
            FactTB.Text = p.FactAddress;
            FaxTB.Text = p.Faks;
            KPPTB.Text = p.KPP;
            LegalTB.Text = p.LegalAddress;
            NameTB.Text = p.Name;
            OKPOTB.Text = p.OKP;
            PhoneTB.Text = p.Telephone;
            DiscTB.Text = p.Discount.ToString();

            

        }
        private void EditFromInfoPanel(Partner p)
        {
            //PartnerInfoPanel.IsEnabled = true;
            p.Code = CodeTB.Text;
            p.Email = EmailTB.Text;
            p.FactAddress = FactTB.Text;
            p.Faks = FaxTB.Text;
            p.KPP = KPPTB.Text;
            p.LegalAddress = LegalTB.Text;
            p.Name = NameTB.Text;
            p.OKP= OKPOTB.Text;
            p.Telephone = PhoneTB.Text;
            int disc = 0;
            if (int.TryParse(DiscTB.Text, out disc) && disc >= 0 && disc <= 100)
                p.Discount = disc;
            
        }
        private void ActionPartnerCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ActionPartnerCombo.SelectedItem == headerCI)
                return;
            if (ActionPartnerCombo.SelectedItem == createOrderCombo)
            {
                Dialogs.NewOrderDialog nod = new Dialogs.NewOrderDialog(PartnerParentTL.SelectedItem as Partner);
                nod.Owner = this;
                nod.ShowDialog();
            }
            ActionPartnerCombo.SelectedItem = headerCI;
        }
        #endregion

        #region Вкладка 1
        //обработчик кнопки в строке 
        private void RemoveOrderButton_Click(object sender, RoutedEventArgs e)
        {
            Order ord = ordersDataGrid.SelectedItem as Order;
            if (ord == null)
                return;

            if (MessageBox.Show(this, "Вы уверены что хотите удалить текущий заказ?", "", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            Data.RemoveOrder(ord);
            ShowOrdersButton_Click(null, null);
            
        }
        private void ShowOrdersButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Partner p = AllFirmsCombo_1.SelectedItem as Partner;
                List<Order> dt;
                if (p.ID_Partner == -1)
                    dt = Data.GetOrders(startDP1.SelectedDate, endDP2.SelectedDate, null);
                else
                    dt = Data.GetOrders(startDP1.SelectedDate, endDP2.SelectedDate, p);
                ordersDataGrid.ItemsSource = dt;
            }
            catch (Exception ex) { ErrorHandler.HandleError(ex.Message); }
        }
        private void CancelOrderButton_Click(object sender, RoutedEventArgs e)
        {
            Order ord = ordersDataGrid.SelectedItem as Order;
            if (ord == null)
                return;

            if (ord.State == "Выполнен")
            {
                ErrorHandler.HandleError("Невозможно отменить заказ, потому что он уже оплачен и выполнен");
                return;
            }

            ord.State = "Отменен";
            Data.UpdateOrder(ord);
            ShowOrdersButton_Click(null, null);
        }
        private void ApplyOrderButton_Click(object sender, RoutedEventArgs e)
        {
            
            Order ord = ordersDataGrid.SelectedItem as Order;
            if (ord == null)
                return;

            if (ord.State == "Отменен")
            {
                ErrorHandler.HandleError("Невозможно выполнить заказ, потому что он отменен");
                return;
            }

            Dialogs.NewInPaymentDialog npd = new Dialogs.NewInPaymentDialog(this, ord);
            npd.ShowDialog();
            ShowOrdersButton_Click(null, null);
        }
        #endregion

        

        #region Вкладка 2 Деньги
        enum KindPayment { Out, In };
        private KindPayment kindPayment = KindPayment.In;
        private void OutMoneyButton_FocusableChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            paymentDG.ItemsSource = null;
           
        }
        private void CreatePaymentButton_Click(object sender, RoutedEventArgs e)
        {
            if (kindPayment == KindPayment.Out)
            {
                Dialogs.NewOutPayment dialog = new Dialogs.NewOutPayment(this);
                dialog.ShowDialog();
            }
            else if (kindPayment == KindPayment.In)
            {
                Dialogs.NewInPaymentDialog dialog = new Dialogs.NewInPaymentDialog(this);
                dialog.ShowDialog();
            }
        }

        private void ShowPaymentButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool b = false;
                if (kindPayment == MainWindow.KindPayment.In)
                    b= true;
                else if (kindPayment == MainWindow.KindPayment.Out)
                    b= false; 
                var list = Data.GetPayments(b, AllPartner_CB2.SelectedItem as Partner,null,
                    StartDate_DP2.SelectedDate,
                    EndDate_DP2.SelectedDate);
                paymentDG.ItemsSource = list;
            }
            catch (Exception ex)
            {
                ErrorHandler.HandleError(ex.Message);
            }
            
        }
        private void OutMoneyButton_Click(object sender, RoutedEventArgs e)
        {
            if (kindPayment == KindPayment.Out)
                return;

            kindPayment = KindPayment.Out;
            paymentDG.ItemsSource = null;
        }

        private void InMoneyButton_Click_Click(object sender, RoutedEventArgs e)
        {
            if (kindPayment == KindPayment.In)
                return;
            kindPayment = KindPayment.In;
            paymentDG.ItemsSource = null;
        }
        private void CancelFilterButton_2_Click(object sender, RoutedEventArgs e)
        {
            StartDate_DP2.SelectedDate = null;
            EndDate_DP2.SelectedDate = null;
            AllPartner_CB2.SelectedItem = null;
        }
        private void ApplyFilterButton_2_Click(object sender, RoutedEventArgs e)
        {
            ShowPaymentButton_Click(null, null);
        }
        private void DeletePaymentButton_Click(object sender, RoutedEventArgs e)
        {
            if (paymentDG.SelectedIndex == -1)
            {
                ErrorHandler.HandleError("Невозможно удалить! Ни одного элемента не выделено.");
                return;// Close();
            }
            Payment p = paymentDG.SelectedItem as Payment;
            if (MessageBox.Show(this,"Вы уверены, что хотите удалить платеж?","Подтверждение удаления",MessageBoxButton.YesNo)== MessageBoxResult.Yes)
                Data.DeletePayment(p);
            ShowPaymentButton_Click(null, null);


        }
        #endregion

        #region Вкладка 3 Склад
        enum StorDo {  move, posting, invent }
        StorDo stordo = StorDo.move;
        

        private void MoveButton_Click(object sender, RoutedEventArgs e)
        {
            if (stordo == StorDo.move)
                return;
            stordo = StorDo.move;

            movedg.Visibility = System.Windows.Visibility.Visible;
            postingdg.Visibility = System.Windows.Visibility.Hidden;
            inventdg.Visibility = System.Windows.Visibility.Hidden;
            Show3Button_Click(null, null);
            
        }

        private void PostingButton_Click(object sender, RoutedEventArgs e)
        {
            if (stordo == StorDo.posting)
                return;
            stordo = StorDo.posting;

            movedg.Visibility = System.Windows.Visibility.Hidden;
            postingdg.Visibility = System.Windows.Visibility.Visible;
            inventdg.Visibility = System.Windows.Visibility.Hidden;
            Show3Button_Click(null, null);
        }

        private void InventButton_Click(object sender, RoutedEventArgs e)
        {
            if (stordo == StorDo.invent)
                return;
            stordo = StorDo.invent;

            movedg.Visibility = System.Windows.Visibility.Hidden;
            postingdg.Visibility = System.Windows.Visibility.Hidden;
            inventdg.Visibility = System.Windows.Visibility.Visible;
            Show3Button_Click(null, null);
        }

        private void Create3Button_Click(object sender, RoutedEventArgs e)
        {
            switch (stordo)
            {
                case StorDo.invent:
                    Dialogs.MoveDialog md1 = new Dialogs.MoveDialog(this,true);
                    md1.ShowDialog();
                    break;
                case StorDo.move:
                    Dialogs.MoveDialog md2 = new Dialogs.MoveDialog(this,false);
                    md2.ShowDialog();
                    break;
                case StorDo.posting:
                    Dialogs.NewOutPayment ne = new Dialogs.NewOutPayment(this);
                    ne.ShowDialog();
                    break;
            }
            Show3Button_Click(null, null);
        }
        private void Show3Button_Click(object sender, RoutedEventArgs e)
        {
            switch (stordo)
            {
                case StorDo.invent:
                    inventdg.ItemsSource = Data.GetInvent(StartDate_DP3.SelectedDate, EndDate_DP3.SelectedDate, Storage3CB.SelectedItem as Storage);
                    return;
                case StorDo.move:
                    movedg.ItemsSource = Data.GetMove(StartDate_DP3.SelectedDate, EndDate_DP3.SelectedDate, Storage3CB.SelectedItem as Storage);
                    return;
                case StorDo.posting:
                    postingdg.ItemsSource = Data.GetOprihod( StartDate_DP3.SelectedDate, EndDate_DP3.SelectedDate,Storage3CB.SelectedItem as Storage);
                    return;
            }
        }
        private void CancelFilterButton_3_Click(object sender, RoutedEventArgs e)
        {
            StartDate_DP3.SelectedDate = null;
            EndDate_DP3.SelectedDate = null;
            Storage3CB.SelectedItem = null;
        }
        private void ApplyFilterButton_3_Click(object sender, RoutedEventArgs e)
        {
            Show3Button_Click(null, null);
        }
        private void Delete3Button_Click(object sender, RoutedEventArgs e)
        {
            
            switch (stordo)
            {
                case StorDo.invent:
                    if (inventdg.SelectedItem as Move == null)
                    {
                        ErrorHandler.HandleError("Не выделено ни одного элемента!!!");
                        return;
                    }
                    try
                    {
                        Data.DeleteMove(inventdg.SelectedItem as Move);
                    }
                    catch (Exception ex) { ErrorHandler.HandleError(ex.Message); }
                    break;
                case StorDo.move:
                    if (movedg.SelectedItem as Move == null)
                    {
                        ErrorHandler.HandleError("Не выделено ни одного элемента!!!");
                        return;
                    }
                    try
                    {
                        Data.DeleteMove(movedg.SelectedItem as Move);
                    }
                    catch (Exception ex) { ErrorHandler.HandleError(ex.Message); }
                    break;
                case StorDo.posting:
                    {
                        ErrorHandler.HandleError("Не выделено ни одного элемента!!!");
                        return;
                    }
                    try
                    {

                    }
                    catch (Exception ex)
                    {
                    }
                    break;
            }
            Show3Button_Click(null, null);
        }
        #endregion


        

        

        


        

























    }
}
